<?php

namespace app\common\model;

use think\Model;
use think\facade\Db;

class Statistics extends Model
{
    protected $name = 'statistics';


    public static function _update($amount, $key): void
    {
        $info = parent::where('key', $key)->find();
        $info->today = $info->today + $amount;
        $info->month = $info->month + $amount;
        $info->year = $info->year + $amount;
        $info->sum = $info->sum + $amount;
        $info->save();
    }

    /**
     * 定时更新统计，需配合定时任务使用
     */
    public static function _timing(): array
    {
        parent::startTrans();
        try {
            $m = date('m');
            $d = date('d');
            if ($m == '01' && $d == '01') {
                Db::execute('update `statistics` set yesterday = today,last_month = `month`,today = 0,`month` = 0,`year` = 0');
            } elseif ($d == '01') {
                Db::execute('update `statistics` set yesterday = today,last_month = `month`,today = 0,`month` = 0');
                Db::execute('update `user` set `month_consume` = 0 where `month_consume` = 1');
            } else {
                Db::execute('update `statistics` set yesterday = today,today = 0');
            }
            parent::commit();

            return ['code' => 1, 'msg' => '更新成功'];
        } catch (\Exception $e) {
            parent::rollback();
            Logs::exception($e);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 此处为演示，是否启用，根据项目而定
     * @return int[]
     */
    public static function getUserCensus(): array
    {
        return [
            '总会员'    => User::where('is_del',0)->count(),
            '正式会员'  => User::where(['is_del'=>0])->where('level_id', '>', 1)->count(),
            '普通会员'  => User::where(['is_del'=>0, 'level_id'=>1])->count(),
        ];
    }

}